package indexingSystem;
import java.util.Scanner;
import java.util.Vector;
import java.util.Hashtable;

import view.*;
import command.*;

public class Interpreter {
	private static View[] views = {
		new ViewTopWords(),
		new ViewTopClusterWords(),
		new ViewFrequency(),
		new ViewClusterFrequency()};

	private static Command defaultCmd = new Help();
	private static Command[] commands = {
				defaultCmd,
				new ReadFolder(),
				new ReadDocument(),
				new Configure(),
				new Commit(),
				new Quit() };
	
	private static Hashtable<String,Command> command_map = null;
	private static Hashtable<String,View> view_map = null;
	
	Interpreter(){
		command_map = new Hashtable<String,Command>();
		for (Command cmd : commands)
			command_map.put(cmd.getCommandName(), cmd);
		view_map = new Hashtable<String,View>();
		for (View view : views)
			view_map.put(view.getCommandName(), view);
	}

	private Vector<String> tokenize(Scanner line) {
		if (!line.hasNext())
			return null;
		Vector<String> tokens = new Vector<String>();
		while (line.hasNext())
			tokens.add(line.next());
		return tokens;
	}
	public static Command[] getCommands() {
			return commands;
	}
	public static View[] getViews() {
		return views;
	}
	public void run() {
		Scanner input = new Scanner(System.in);
		Scanner line;
		String cmdName;
		while(input.hasNextLine()) {	
			line = new Scanner(input.nextLine());
			if (!line.hasNext()) {
				line.close();
				continue;
			}
			cmdName = line.next();
			try {
				if (command_map.containsKey(cmdName)) {
					Command cmd = command_map.get(cmdName);
					if (cmd.commandHasArgs())
						cmd.execute(tokenize(line));
					else {
						if(line.hasNext())
							cmd.getCommandUsage();
						else
							cmd.execute(null);
					}
				} else if (view_map.containsKey(cmdName)) {
					View view = view_map.get(cmdName);
					view.show();
				} else
					defaultCmd.execute(null);
			} catch (Exception e) {
				System.err.println(e.toString());
				line.close();
			}
		Logger.getLog().flush();	
		}
	}
}
